package com.sun.xacml.combine;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.sun.xacml.AbstractPolicy;
import com.sun.xacml.EvaluationCtx;
import com.sun.xacml.MatchResult;
import com.sun.xacml.ctx.Result;
import com.sun.xacml.ctx.Status;

public class ORPolicyAlg extends PolicyCombiningAlgorithm{

	public static final String algId =
        "urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:" +
        "or";

    // a URI form of the identifier
    private static URI identifierURI;
    // exception if the URI was invalid, which should never be a problem
    private static RuntimeException earlyException;

    static {
        try {
            identifierURI = new URI(algId);
        } catch (URISyntaxException se) {
            earlyException = new IllegalArgumentException();
            earlyException.initCause(se);
        }
    }

    /**
     * Standard constructor.
     */
    public ORPolicyAlg() {
        super(identifierURI);

        if (earlyException != null)
            throw earlyException;
    }

    /**
     * Protected constructor used by the ordered version of this algorithm.
     *
     * @param identifier the algorithm's identifier
     */
    protected ORPolicyAlg(URI identifier) {
        super(identifier);
    }
	@Override
	public Result combine(EvaluationCtx context, List policies) {
		   	boolean atLeastOneError = false;
	        boolean atLeastOneDeny = false;
	        boolean atLeastOnePermit = false;
	        Set denyObligations = new HashSet();
	        Set permitObligations = new HashSet();
	        Status firstIndeterminateStatus = null;
	        Iterator it = policies.iterator();

	        while (it.hasNext()) {
	            AbstractPolicy policy = (AbstractPolicy)(it.next());

	            // make sure that the policy matches the context
	            MatchResult match = policy.match(context);

	            if (match.getResult() == MatchResult.INDETERMINATE) {
	                atLeastOneError = true;
	                
	                // keep track of the first error, regardless of cause
	                if (firstIndeterminateStatus == null)
	                    firstIndeterminateStatus = match.getStatus();
	            } else if (match.getResult() == MatchResult.MATCH) {
	                // now we evaluate the policy
	                Result result = policy.evaluate(context);
	                int effect = result.getDecision();
	                
	                // this is a little different from DenyOverrides...
	                if (effect == Result.DECISION_PERMIT){
	                    atLeastOnePermit = true;
	                    permitObligations.addAll(result.getObligations());
	                }
	                
	                //if permit or deny then get obligaiton to considering later 
	                if (effect == Result.DECISION_DENY) {
	                    atLeastOneDeny = true;
	                    denyObligations.addAll(result.getObligations());
	                } else if (effect == Result.DECISION_INDETERMINATE) {
	                    atLeastOneError = true;

	                    // keep track of the first error, regardless of cause
	                    if (firstIndeterminateStatus == null)
	                        firstIndeterminateStatus = result.getStatus();
	                }
	            }
	        }
	    
	        // if we got a DENY and a permit then indeterminate
	        if(atLeastOnePermit && atLeastOneDeny)
	        	return new Result(Result.DECISION_INDETERMINATE,
                        firstIndeterminateStatus,
                        context.getResourceId().encode());
	        
	        if (atLeastOneDeny)
	            return new Result(Result.DECISION_DENY,
	                              context.getResourceId().encode(),
	                              denyObligations);
	        if (atLeastOnePermit)
	            return new Result(Result.DECISION_PERMIT,
	                              context.getResourceId().encode(),
	                              permitObligations);
	        
	        
	        // if we got an INDETERMINATE, return it
	        if (atLeastOneError)
	            return new Result(Result.DECISION_INDETERMINATE,
	                              firstIndeterminateStatus,
	                              context.getResourceId().encode());
	        
	        // if we got here, then nothing applied to us
	        return new Result(Result.DECISION_NOT_APPLICABLE,
	                          context.getResourceId().encode());
	    }
	

}
